package HandleXml.service;

import  HandleXml.model.Book;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jdom2.input.SAXBuilder;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookReadService {
    private static final String XML_FILE = "src/main/resources/books.xml";

    @Test
    public void testDom4j(){
        List<Book> books = readBooksWithDom4j();
        printBookInfo(books);
    }

    @Test
    public void testJdom(){
        List<Book> books = readBooksWithJdom();
        printBookInfo(books);
    }


    // 使用DOM4J读取XML并转换为Book对象列表
    public static List<Book> readBooksWithDom4j() {
        List<Book> books = new ArrayList<>();
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(XML_FILE));
            Element root = document.getRootElement();

            // 获取所有book元素
            List<Element> bookElements = root.elements("book");
            for (Element bookElement : bookElements) {
                Book book = new Book();
                
                // 设置基本属性
                book.setId(bookElement.attributeValue("id"));
                book.setCategory(bookElement.attributeValue("category"));
                
                // 设置标题
                Element titleElement = bookElement.element("title");
                Book.Title title = new Book.Title();
                title.setValue(titleElement.getText());
                title.setLang(titleElement.attributeValue("lang"));
                book.setTitle(title);

                // 设置作者信息
                Element authorElement = bookElement.element("author");
                Book.Author author = new Book.Author();
                author.setName(authorElement.elementText("name"));
                author.setNationality(authorElement.elementText("nationality"));
                author.setEmail(authorElement.elementText("email"));
                book.setAuthor(author);

                // 设置出版社信息（带命名空间）
                Element publisherElement = bookElement.element("publisher");
                if (publisherElement != null) {
                    Book.Publisher publisher = new Book.Publisher();
                    publisher.setName(publisherElement.elementText("name"));
                    publisher.setAddress(publisherElement.elementText("address"));
                    book.setPublisher(publisher);
                }

                // 设置价格和货币
                Element priceElement = bookElement.element("price");
                if (priceElement != null) {
                    Book.Price price = new Book.Price();
                    price.setValue(Double.parseDouble(priceElement.getText()));
                    price.setCurrency(priceElement.attributeValue("currency"));
                    book.setPrice(price);
                }

                // 设置描述（CDATA内容）
                book.setDescription(bookElement.elementText("description"));
                
                // 设置出版日期
                book.setPubdate(bookElement.elementText("pubdate"));

                books.add(book);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return books;
    }

    // 使用JDOM2读取XML并转换为Book对象列表
    public static List<Book> readBooksWithJdom() {
        List<Book> books = new ArrayList<>();
        try {
            SAXBuilder builder = new SAXBuilder();
            org.jdom2.Document document = builder.build(new File(XML_FILE));
            org.jdom2.Element root = document.getRootElement();

            // 获取所有book元素
            List<org.jdom2.Element> bookElements = root.getChildren("book");
            for (org.jdom2.Element bookElement : bookElements) {
                Book book = new Book();
                
                // 设置基本属性
                book.setId(bookElement.getAttributeValue("id"));
                book.setCategory(bookElement.getAttributeValue("category"));
                
                // 设置标题
                org.jdom2.Element titleElement = bookElement.getChild("title");
                Book.Title title = new Book.Title();
                title.setValue(titleElement.getText());
                title.setLang(titleElement.getAttributeValue("lang"));
                book.setTitle(title);

                // 设置作者信息
                org.jdom2.Element authorElement = bookElement.getChild("author");
                Book.Author author = new Book.Author();
                author.setName(authorElement.getChildText("name"));
                author.setNationality(authorElement.getChildText("nationality"));
                author.setEmail(authorElement.getChildText("email"));
                book.setAuthor(author);

                // 设置出版社信息（带命名空间）
                Namespace pubNs = Namespace.getNamespace("pub", "http://www.publisher.org");
                org.jdom2.Element publisherElement = bookElement.getChild("publisher", pubNs);
                if (publisherElement != null) {
                    Book.Publisher publisher = new Book.Publisher();
                    publisher.setName(publisherElement.getChildText("name", pubNs));
                    publisher.setAddress(publisherElement.getChildText("address", pubNs));
                    book.setPublisher(publisher);
                }

                // 设置价格和货币
                org.jdom2.Element priceElement = bookElement.getChild("price");
                if (priceElement != null) {
                    Book.Price price = new Book.Price();
                    price.setValue(Double.parseDouble(priceElement.getText()));
                    price.setCurrency(priceElement.getAttributeValue("currency"));
                    book.setPrice(price);
                }

                // 设置描述（CDATA内容）
                book.setDescription(bookElement.getChildText("description"));
                
                // 设置出版日期
                book.setPubdate(bookElement.getChildText("pubdate"));

                books.add(book);
            }

        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
        return books;
    }

    // 测试方法
    public static void printBookInfo(List<Book> books) {
        for (Book book : books) {
            System.out.println("\n=== 图书信息 ===");
            System.out.println("ID: " + book.getId());
            System.out.println("类别: " + book.getCategory());
            System.out.println("标题: " + book.getTitle().getValue());
            System.out.println("语言: " + book.getTitle().getLang());
            System.out.println("作者: " + book.getAuthor().getName());
            System.out.println("国籍: " + book.getAuthor().getNationality());
            if (book.getAuthor().getEmail() != null) {
                System.out.println("邮箱: " + book.getAuthor().getEmail());
            }
            if (book.getPublisher() != null) {
                System.out.println("出版社: " + book.getPublisher().getName());
                System.out.println("地址: " + book.getPublisher().getAddress());
            }
            System.out.println(String.format("价格: %.2f %s", book.getPrice(), book.getCurrency()));
            System.out.println("描述: " + book.getDescription());
            System.out.println("出版日期: " + book.getPubdate());
        }
    }
}